<template>
  <div class="role-management">
    <!-- Tab 菜单栏 -->
    <el-tabs v-model="activeTab" class="tabs-menu">
      <el-tab-pane label="角色管理" name="role-management">
        <!-- 角色管理内容 -->
        <el-card class="role-card" shadow="hover">
          <div slot="header" class="clearfix role-header">
            <span class="role-title">角色管理</span>
            <el-button type="primary" @click="openRoleDialog" size="small" class="role-create-btn">新建角色</el-button>
          </div>

          <hr class="table-divider" />

          <el-table :data="roles" style="width: 100%;" border>
            <el-table-column prop="name" label="角色名称"></el-table-column>
            <el-table-column label="权限">
              <template #default="scope">
                <el-button @click="openPermissionDialog(scope.row)" size="small" type="primary" plain icon="Key">
                  分配权限
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button link @click="editRole(scope.row)" size="small" type="warning">编辑</el-button>
                <el-button link @click="deleteRole(scope.row)" type="danger" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination :current-page="currentPage" :page-size="pageSize" :total="total" :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper" @current-change="handlePageChange"
            @size-change="handleSizeChange" class="pagination" />
        </el-card>
      </el-tab-pane>



      <el-tab-pane label="用户管理" name="user-management">
        <!-- 用户管理内容 -->
        <el-card class="user-card" shadow="hover">
          <div slot="header" class="clearfix user-header">
            <span class="user-title">用户管理</span>
            <el-button type="primary" @click="openUserDialog" size="small" class="user-create-btn">新建用户</el-button>
          </div>

          <hr class="table-divider" />

          <!-- 用户管理内容 -->
          <el-table :data="users" style="width: 100%;" border>
            <el-table-column prop="avatar" label="头像" min-width="15px">
              <template #default="scope">
                <!-- 使用 el-image 组件显示头像 -->
                <el-image :src="scope.row.avatar" alt="头像" style="width: 40px; height: 40px; border-radius: 50%;"
                  fit="cover" />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="用户名"></el-table-column>
            <el-table-column prop="nickname" label="昵称"></el-table-column>
            <el-table-column label="角色">
              <template #default="scope">
                <el-button @click="addRole(scope.row)" size="small" type="primary" plain icon="Key">
                  分配角色
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button link @click="editRole(scope.row)" size="small" type="warning">编辑</el-button>
                <el-button link @click="deleteRole(scope.row)" type="danger" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 分配权限弹窗（保持原样） -->
    <el-dialog :title="'分配权限 - ' + (currentRole ? currentRole.name : '')" v-model="permissionDialogVisible" width="70%"
      center>
      <div class="permission-container">
        <div class="permission-grid-item" v-for="permission in permissionOptions" :key="permission.id">
          <el-card shadow="hover" class="permission-card-item"
            :class="{ 'is-active': selectedPermissions.includes(permission.id) }" @click="togglePermission(permission)">
            <div class="card-content">
              <el-checkbox :model-value="selectedPermissions.includes(permission.id)" class="permission-checkbox">
                {{ permission.name }}
              </el-checkbox>
              <p class="permission-description">{{ permission.description || '暂无描述' }}</p>
            </div>
          </el-card>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePermissions">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 角色管理弹窗 -->
    <el-dialog :title="newRole.id ? '编辑角色' : '新建角色'" v-model="roleDialogVisible" width="500px" center>
      <el-form label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="newRole.name" placeholder="请输入角色名称" clearable show-word-limit maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="newRole.description" placeholder="请输入角色描述" clearable show-word-limit
            maxlength="100"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRole">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import request from '@/utils/request'; // 建议统一使用 request 封装
import { ElMessage } from 'element-plus';

// Data
const roles = ref([]); 
const roleList = ref([]); // 角色列表，用于分配角色
const users = ref([]); 
const total = ref(0); // 独立的总数变量
const permissionDialogVisible = ref(false);
const roleDialogVisible = ref(false);
const selectedPermissions = ref([]); 
const newRole = ref({ name: '', description: '', id: null });
const currentRole = ref(null); 
const currentUser = ref(null); // 当前选中的用户，用于分配角色
const currentPage = ref(1); 
const pageSize = ref(10); 
const permissionOptions = ref([]);
const activeTab = ref('role-management'); // 当前选中的 tab

// 获取角色分页
const fetchRoles = async (current = currentPage.value, size = pageSize.value) => {
  try {
    const response = await request.get('/role/page', {
      params: { current, size }
    });
    roles.value = response.data.data.records;
    total.value = response.data.data.total; 
  } catch (error) {
    console.error("Failed to fetch roles", error);
  }
};

// 获取用户分页
const fetchUsers = async (current = currentPage.value, size = pageSize.value) => {
  try {
    const response = await request.get('/user/getUserPage', {
      params: { current, size }
    });
    users.value = response.data.data.records;
    total.value = response.data.data.total; 
  } catch (error) {
    console.error("Failed to fetch users", error);
  }
};

// 获取所有权限选项
const fetchPermissions = async () => {
  try {
    const response = await request.get('/role/permissionList');
    permissionOptions.value = response.data.data;
  } catch (error) {
    console.error("Failed to fetch permissions", error);
  }
};

// 分页操作
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchRoles();
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchRoles();
};

// 打开新建角色弹窗
const openRoleDialog = () => {
  newRole.value = { name: '', description: '', id: null }; // 重置
  roleDialogVisible.value = true;
};

// 打开编辑角色弹窗
const editRole = (role) => {
  newRole.value = { name: role.name, description: role.description, id: role.id }; // 填充数据
  roleDialogVisible.value = true;
};

// 获取角色权限
const getPermissionsByRoleId = async (roleId) => {
  try {
    const response = await request.get(`/role/getPerByRoleId`, { params: { roleId } });
    selectedPermissions.value = response.data.data.map(item => item.permissionId) || [];
  } catch (error) {
    ElMessage.error(error.message || '获取角色权限失败');
  }
};

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const response = await request.get('/role/list');
    roleList.value = response.data.data || [];
  } catch (error) {
    console.error("Failed to fetch roles", error);
  }
};

// 打开角色分配弹窗
const addRole = async (user) => {
  currentUser.value = user;
  roleDialogVisible.value = true;
};

// 打开权限分配弹窗
const openPermissionDialog = async (role) => {
  currentRole.value = role;
  await getPermissionsByRoleId(role.id);
  permissionDialogVisible.value = true;
};

// 切换权限选中状态
const togglePermission = (permission) => {
  const index = selectedPermissions.value.indexOf(permission.id);
  if (index === -1) {
    selectedPermissions.value.push(permission.id);
  } else {
    selectedPermissions.value.splice(index, 1);
  }
};

// 保存权限
const savePermissions = async () => {
  const data = {
    roleId: currentRole.value.id,
    permissionIds: selectedPermissions.value
  };
  try {
    await request.post(`/role/addPermission`, data);
    ElMessage.success('分配权限成功');
    permissionDialogVisible.value = false;
    fetchRoles(currentPage.value, pageSize.value);
  } catch (error) {
    ElMessage.error(error.message || '分配权限失败');
  }
};

// 保存角色
const saveRole = async () => {
  try {
    if (newRole.value.id) {
      await request.put('/role/edit', newRole.value);
    } else {
      await request.post('/role/add', newRole.value);
    }
    roleDialogVisible.value = false;
    fetchRoles();
  } catch (error) {
    console.error(error);
  }
};

// 删除角色
const deleteRole = async (role) => {
  try {
    await request.delete(`/roles/${role.id}`);
    fetchRoles();
  } catch (error) {
    console.error(error);
  }
};

onMounted(() => {
  fetchRoles();
  fetchPermissions();
  fetchUsers();
  fetchRoleList();
});
</script>

<style scoped>
.role-management {
  margin: 30px;
}

.role-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.role-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.permission-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
  padding: 10px;
}

.permission-card-item {
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.2s ease;
  border: 1px solid #ebeef5;
  height: 100%;
}

.permission-card-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #c6e2ff;
}

.permission-card-item.is-active {
  border-color: #409eff;
  background-color: #ecf5ff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.card-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 5px;
}

.permission-checkbox {
  font-weight: bold;
  margin-bottom: 8px;
  pointer-events: none; 
}

.permission-description {
  font-size: 13px;
  color: #909399;
  line-height: 1.4;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.table-divider {
  border: 0;
  border-top: 1px solid #e4e7ed;
  margin-top: 20px;
  margin-bottom: 20px;
}
.el-button {
  font-size: 14px;
}
.user-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.user-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}
</style>
